<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="logo-container">
        <img src="../assets/logo.png" alt="Logo" class="logo">
        <h2>MBTI职业性格测试系统</h2>
      </div>
      
      <el-form
        ref="formRef"
        :model="loginForm"
        :rules="rules"
        label-position="top"
      >
        <el-form-item label="学号/教师号" prop="usercode">
          <el-input
            v-model="loginForm.usercode"
            placeholder="请输入学号或教师号"
            prefix-icon="Document"
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" class="login-button" @click="handleLogin">
            登录
          </el-button>
        </el-form-item>

        <div class="register-link">
          还没有账号？
          <router-link to="/register">立即注册</router-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'LoginPage'
}
</script>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()
const formRef = ref(null)

const loginForm = ref({
  usercode: '',
  password: ''
})

const rules = {
  usercode: [
    { required: true, message: '请输入学号或教师号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 组件挂载时清除旧的认证信息
onMounted(() => {
  // 清除localStorage中的token和用户信息，确保重新登录
  localStorage.removeItem('token')
  localStorage.removeItem('userInfo')
  userStore.setToken('')
  userStore.setUserInfo(null)
})

const handleLogin = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    const response = await userStore.login(loginForm.value)
    
    // 检查响应结构
    console.log('Login response:', response)
    
    // 由于request.js中的响应拦截器已经处理了response，这里直接使用返回的数据
    if (response && response.data) {
      const userData = response.data
      ElMessage.success(response.message || '登录成功')
      
      // 根据用户类型跳转到不同页面
      const userType = userData.userType ? userData.userType.toLowerCase() : ''
      console.log('User type detected:', userType)
      
      if (userType === 'student') {
        router.push('/student/profile')
      } else if (userType === 'teacher') {
        router.push('/teacher/profile')
      } else if (userType === 'super_admin') {
        // 超级管理员跳转到管理员页面
        router.push('/teacher/profile') // 或者其他适合管理员的页面
      } else {
        console.error('Unknown user type:', userData.userType)
        ElMessage.error('未知的用户类型')
      }
    } else {
      console.error('Invalid user data:', response)
      ElMessage.error('获取用户数据失败')
    }
  } catch (error) {
    console.error('Login error:', error)
    
    // 检查是否是教师审批相关错误
    if (error.message && (
      error.message.includes('教师账号正在审核中') || 
      error.message.includes('教师账号审核未通过')
    )) {
      ElMessage.error({
        message: error.message,
        duration: 5000
      })
    } else {
      ElMessage.error(error.response?.message || error.message || '登录失败')
    }
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

.login-card {
  width: 400px;
  padding: 20px;
}

.logo-container {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  width: 100px;
  height: 100px;
  margin-bottom: 10px;
}

.login-button {
  width: 100%;
}

.register-link {
  text-align: center;
  margin-top: 15px;
  font-size: 14px;
}

.register-link a {
  color: #409eff;
  text-decoration: none;
}

.register-link a:hover {
  text-decoration: underline;
}
</style> 